#ifndef __YHM_TOOLS_H__
#define __YHM_TOOLS_H__

#include "types.h"
#include "memtool.h"
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <infiniband/verbs.h>

#define BUILD_BUG_ON(condition) ((void)sizeof(char[1 - 2*!!(condition)]))
#define UNUSED(x) ((void)(x))
#define p_info(fmt, ...) printf(fmt, ##__VA_ARGS__);
#define p_err(fmt, ...) fprintf(stderr, fmt, ##__VA_ARGS__);
#define p_die(fmt, ...) {fprintf(stderr, fmt, ##__VA_ARGS__); assert(0);}


struct bitmap{
  unsigned long bit[0];
};
static inline int getbit(struct bitmap *bm, int pos){
  return 1&(bm->bit[pos>>6] >> (pos & 63));
}
static inline void setbit(struct bitmap *bm, int pos){
  bm->bit[pos>>6] |= 1UL << (pos & 63);
}
static inline void clearbit(struct bitmap *bm,int pos){
  bm->bit[pos>>6] &= ~(1UL << (pos & 63));
}

static inline void mt_wait_key(struct mc_ctx *mi, const char *key){
  while(mt_get(mi, key, NULL, NULL))usleep(1000);
}
static inline void mt_wait_key_val(struct mc_ctx *mi, const char *key, const char *val){
  char *v;
  int res;
  assert(key && val);
  for(;;){
    res = mt_get(mi, key, &v, NULL);
    usleep(1000);
    if(res)continue;
    if(!strcmp(v, val)){
      free(v);
      break;
    }
    free(v);
  }
}
static inline char* itoa(int num,char* str,int radix)
{
    char index[] = "0123456789ABCDEF";
    unsigned unum;
    int i=0,j,k;
    if(radix == 10 && num < 0){
        unum=(unsigned) -num;
        str[i++] = '-';
    }
    else unum = (unsigned)num;
    do{
        str[i++] = index[unum % (unsigned)radix];
        unum /= radix;
       }while(unum);
    str[i] = '\0';
    if(str[0] == '-') k=1;
    else k=0;
    for(j = k; j <= (i - 1) / 2;j ++)
    {       
      char temp;
      temp=str[j];
      str[j]=str[i-1+k-j];
      str[i-1+k-j]=temp;
    }
    return str;
}

#endif